<template>
  <div>
    <Tabs v-model="tabParam.heavyOrEmpty">
      <template v-for="item in containerStatues">
        <TabPane :label="item.label" :name="item.val"></TabPane>
      </template>
    </Tabs>
    <Row v-if="+tabParam.heavyOrEmpty ==1">
      <i-col>
        <Form ref="tabParam" :model="tabParam" label-position="right" inline>
          <FormItem>
            <Button type="primary" @click="exportDataInventory">
              <Icon type="ios-download-outline"></Icon>
              导出原始数据
            </Button>
          </FormItem>
          <FormItem label="绑箱时间：">
            <DatePicker v-model="timeSlot.timeVal" type="daterange" :options="timeSlot.timeOptions" split-panels
                        placeholder="绑箱时间" format="yyyy年MM月dd日" style="width: 230px">
            </DatePicker>
          </FormItem>
          <FormItem label="送货地址：">
            <Input type="text" v-model="tabParam.shippingAddress" placeholder="送货地址"></Input>
          </FormItem>

          <FormItem label="货物名称：">
            <Input type="text" v-model="tabParam.productName" placeholder="品名"></Input>
          </FormItem>
          <FormItem label="集装箱号：">
            <Input type="text" v-model="tabParam.containerNoBody" placeholder="集装箱号"></Input>
          </FormItem>
          <FormItem label="联运单号：" prop="mainOrderNo">
            <Input type="text" v-model="tabParam.mainOrderNo" placeholder="联运单号"></Input>
          </FormItem>
          <FormItem label="车队：" v-if="roleType === 1">
            <Select v-model="tabParam.trackName" style="width:160px" clearable>
              <Option v-for="item in trackName" :value="item.id" :key="item.id">{{ item.login_name }}</Option>
            </Select>
          </FormItem>
          <FormItem label="运单状态：">
            <Select v-model="tabParam.status" multiple>
              <Option v-for="item in orderStatues" :value="item.val" :key="item.val">{{ item.label }}</Option>
            </Select>
          </FormItem>
          <FormItem>
            <Button type="primary" @click="handleSearch" icon="ios-search">
              搜索
            </Button>
          </FormItem>
        </Form>
        <div class="total">
          <label>统计：</label>
          箱数：<span v-text="totalData.containerNum"></span>，
          运费总和：<span v-text="totalData.totalFee"></span>
        </div>
        <tablePage ref="orderReportNewTab" :api="orderLiquidationByPage" :param="tabParam">
          <template slot-scope="props">
            <Table :columns="containerColumn" :data="props.data"></Table>
          </template>
        </tablePage>
      </i-col>
    </Row>
    <Row v-if="+tabParam.heavyOrEmpty ==0">
      <i-col>
        <noLoadContainers></noLoadContainers>
      </i-col>
    </Row>
  </div>
</template>
<script>
  import noLoadContainers from './components/noLoadContainers'
  import tablePage from '@components/table/tablePage.vue'
  import { orderLiquidationByPage, orderLiquidationTotal } from '@api/backEnd/report'
  import { getOwnFleet } from '@api/backEnd/station'
  import { exportUtil } from '@/vendor/exportInvoke'
  import { mapGetters } from 'vuex'
  import moment from 'moment'

  export default {
    name: '',
    data () {
      let addressList = []
      let timeTypes = {
        startTime: 0,
        endTime: 1
      }
      let roleType = 1
      let containerStatues = [
        { label: '重箱出场', val: '1' },
        { label: '非重箱出场', val: '0' }
      ]
      let orderStatues = [
        { label: '未到', val: '3,4,5' },
        { label: '已到', val: '1,2' },
        { label: '已完成', val: '6' }
      ]
      let timeSlot = {
        timeOptions: {
          shortcuts: [
            {
              text: '最近一周 ',
              value () {
                let end = new Date()
                let start = new Date()
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
                return [start, end]
              }
            },
            {
              text: '最近一月',
              value () {
                let end = new Date()
                let start = new Date()
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
                return [start, end]
              }
            },
            {
              text: '最近三个月',
              value () {
                let end = new Date()
                let start = new Date()
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
                return [start, end]
              }
            }
          ]
        },
        timeVal: [moment().subtract(7, 'days').format('YYYY-MM-DD') + ' 00:00:00', moment().format('YYYY-MM-DD') + ' 00:00:00']
      }
      let trackName = []
      let tabParam = {
        mainOrderNo: '',
        productName: '',
        containerNoBody: '',
        shippingAddress: '',
        trackName: '',
        fleetId: '',
        status: [],
        heavyOrEmpty: containerStatues[0].val,
        bindTimeStart: timeSlot.timeVal[0],
        bindTimeEnd: timeSlot.timeVal[1],
        isFleet: false
      }
      let containerColumn = [
        {
          title: '联运单号',
          key: 'main_order_no',
          ellipsis: 'false',
          fixed: 'left',
          width: 200
        },
        {
          title: '子单号',
          ellipsis: 'false',
          key: 'order_no',
          width: 200
        },
        {
          title: '货票号',
          ellipsis: 'false',
          key: 'waybill_no',
          width: 100
        },
        {
          title: '集装箱号',
          ellipsis: 'false',
          key: 'container_no_body',
          width: 140,
          render: (h, params) => {
            let thisdata = params.row.container_no_head + params.row.container_no_body
            return (<span>{thisdata}</span>)
          }
        },
        {
          title: '发货人',
          ellipsis: 'false',
          key: 'shipper',
          width: 200
        },
        {
          title: '收货人',
          ellipsis: 'false',
          key: 'receiver',
          width: 200
        },
        {
          title: '货物名称',
          ellipsis: 'false',
          key: 'zkpmhz0',
          width: 100
        },
        {
          title: '发站',
          ellipsis: 'false',
          key: 'start_station_name',
          width: 100
        },
        {
          title: '到站',
          ellipsis: 'false',
          key: 'end_station_name',
          width: 100
        },
        {
          title: '发站时间',
          ellipsis: 'false',
          key: 'start_station_time',
          width: 150,
          render: (h, params) => {
            let thisdata = params.row.start_station_time
            thisdata = thisdata ? moment(thisdata).format('YYYY-MM-DD HH:mm') : ''
            return (<span>{thisdata}</span>)
          }
        },
        {
          title: '到站时间',
          ellipsis: 'false',
          key: 'end_station_time',
          width: 150,
          render: (h, params) => {
            let thisdata = params.row.end_station_time
            thisdata = thisdata ? moment(thisdata).format('YYYY-MM-DD HH:mm') : ''
            return (<span>{thisdata}</span>)
          }
        },
        {
          title: '子运单状态',
          ellipsis: 'false',
          key: 'bind_time',
          width: 150,
          render: (h, params) => {
            let item = params.row
            let txt = ''
            let color = ''
            if (item.voucher_img && item.fleet_id && item.driver_id) {
              txt = '已完成'
              color = 'green'
            } else if (item.fleet_id && item.driver_id && item.shipping_address) {
              txt = '配送中'
              color = 'yellow'
            } else if (item.fleet_id) {
              txt = '待配送'
              color = 'blue'
            } else if (!item.fleet_id && !item.driver_id) {
              txt = '待拉运'
              color = 'red'
            }
            return (<tag type="dot" color={color}>{txt}</tag>)
          }
        },
        {
          title: '绑箱时间',
          ellipsis: 'false',
          key: 'bind_time',
          width: 150,
          render: (h, params) => {
            let thisdata = params.row.bind_time
            thisdata = thisdata ? moment(thisdata).format('YYYY-MM-DD HH:mm') : ''
            return (<span>{thisdata}</span>)
          }
        },
        {
          title: '司机名称',
          ellipsis: 'false',
          key: 'driver_name',
          width: 100
        },
        {
          title: '车牌号',
          ellipsis: 'false',
          key: 'truck_plate',
          width: 100
        },
        {
          title: '送货地址',
          ellipsis: 'false',
          key: 'shipping_address',
          width: 100
        },
        {
          title: '接取送达费',
          ellipsis: 'false',
          key: 'zkjf018',
          width: 100
        }
      ]
      let totalData = {
        containerNum: 0,
        totalFee: 0
      }
      let datas = {
        tabParam,
        containerColumn,
        orderLiquidationByPage,
        containerStatues,
        timeTypes,
        timeSlot,
        addressList,
        trackName,
        roleType,
        orderStatues,
        totalData
      }
      return datas
    },
    methods: {
      handleSearch (param) {
        /*  param.pageSize = param.pageSize =
         orderLiquidationByPage(param).then(res => {
         // console.log(this.searchForm + ' --- searchForm')
         if (res.data.isSuccess === 1) {
         this.main_order_list = res.data.data.list
         this.pageTotal = res.data.data.total
         }
         }) */
        this.calculateTotalValues(this.tabParam)
        this.$refs['orderReportNewTab'].dataRefresh()
      },
      calculateTotalValues (tabParams) {
        orderLiquidationTotal(tabParams).then(res => {
          console.log(res)
          if (res.data.isSuccess === 1) {
            this.totalData = {
              containerNum: res.data.data.containerNum,
              totalFee: res.data.data.totalFee
            }
          }
        })
      },
      exportDataInventory () {
        let param = Object.assign({}, this.tabParam)
        param.page = 1
        param.pageSize = 100000
        orderLiquidationByPage(param).then(res => {
          if (res.data.isSuccess === 1) {
            let resDate = res.data.data.rows
            // let resColumns = JSON.parse(JSON.stringify(this.stationColumn))
            let result = this.fasetJson(resDate)
            exportUtil.export2Excel('业务报表', result.columns, result.data)
          }
        })
      },
      fasetJson (tabData) {
        let result = {
          columns: [
            { title: '联运单号', key: 'main_order_no' },
            { title: '子单号', key: 'order_no' },
            { title: '货票号', key: 'waybill_no' },
            { title: '集装箱号', key: 'container_no_body' },
            { title: '发货人', key: 'shipper' },
            { title: '收货人', key: 'receiver' },
            { title: '货物名称', key: 'product_name' },
            { title: '发站', key: 'start_station_name' },
            { title: '到站', key: 'end_station_name' },
            { title: '发站时间', key: 'start_station_time' },
            { title: '到站时间', key: 'end_station_time' },
            { title: '子运单状态', key: 'status' },
            { title: '绑箱时间', key: 'bind_time' },
            { title: '司机名称', key: 'driver_name' },
            { title: '车牌号', key: 'truck_plate' },
            { title: '送货地址', key: 'shipping_address' },
            { title: '接取送达费', key: 'zkjf018' }
          ],
          data: []
        }
        let indexCount = 0
        tabData.forEach((item) => {
          if (item.voucher_img && item.fleet_id && item.driver_id) {
            item.status = '已完成'
          } else if (item.fleet_id && item.driver_id && item.shipping_address) {
            item.status = '配送中'
          } else if (item.fleet_id) {
            item.status = '待配送'
          } else if (!item.fleet_id && !item.driver_id) {
            item.status = '待拉运'
          }
          item.container_no_body = item.container_no_head + item.container_no_body
          let dataItem = {
            main_order_no: item.main_order_no,
            order_no: item.order_no,
            waybill_no: item.waybill_no,
            container_no_body: item.container_no_body,
            shipper: item.shipper,
            receiver: item.receiver,
            product_name: item.product_name,
            start_station_name: item.start_station_name,
            end_station_name: item.end_station_name,
            start_station_time: item.start_station_time,
            end_station_time: item.end_station_time,
            status: item.status,
            bind_time: item.bind_time,
            driver_name: item.driver_name,
            truck_plate: item.truck_plate,
            shipping_address: item.shipping_address,
            zkjf018: item.zkjf018
          }
          result.data.push(dataItem)
          indexCount++
        })
        console.log(indexCount)
        return result
      }
    },
    watch: {
      'timeSlot.timeVal': function (val, oldval) {
        if (val && val[0] && val[1]) {
          this.tabParam.bindTimeStart = moment(val[0]).format('YYYY-MM-DD') + ' 00:00:00'
          this.tabParam.bindTimeEnd = moment(val[1]).format('YYYY-MM-DD') + ' 23:59:59'
        } else {
          delete this.tabParam.bindTimeStart
          delete this.tabParam.bindTimeEnd
        }
      }
    },
    mounted () {
      if (this.currentUser.role.indexOf('车队') !== -1) {
        this.roleType = 2
      }
      if (this.roleType === 1) {
        getOwnFleet().then(res => {
          if (res.data.isSuccess === 1) {
            this.trackName = res.data.data
          }
        })
      }
      if (powerUtil.contains('comingFleet')) {
        this.tabParam.isFleet = true
      }
      this.calculateTotalValues(this.tabParam)
    },
    computed: {
      ...mapGetters(['currentUser'])
    },
    components: { tablePage, noLoadContainers }
  }
</script>
<style scoped>
  .lh-32 {
    line-height: 32px;
    margin-right: 5px;
  }

  .total {
    margin-bottom: 10px;
  }

  .total label {
    font-weight: bold;
  }
</style>
